﻿#include "MonitorDeviderItem.h"
#include "MonitorDeviderWidget.h"
#include <QMouseEvent>
#include <QDebug>
#include <QPainter>

MonitorDeviderItem::MonitorDeviderItem(QWidget *parent)
  : QWidget {parent}
  , mSelected(false)
  , mFullScreen {false} {}

void MonitorDeviderItem::mousePressEvent(QMouseEvent *event) {
    if(event->button() == Qt::MouseButton::LeftButton) {
        auto object = qobject_cast<MonitorDeviderWidget *>(parent());

        for(auto &item: object->mItems) {
            item == this ? item->setSelected(true) : item->setSelected(false);
        }
    }
}

void MonitorDeviderItem::mouseDoubleClickEvent(QMouseEvent *event) {
    if(event->button() == Qt::MouseButton::LeftButton) {
        auto object = qobject_cast<MonitorDeviderWidget *>(parent());
        auto count  = std::count_if(object->mItems.begin(), object->mItems.end(), [](const MonitorDeviderItem *item) { return item->fullScreen(); });
        if(count) {
            for(auto &item: object->mItems) {
                item->setFullScreen(false);
            }
        } else {
            for(auto &item: object->mItems) {
                item == this ? item->setFullScreen(true) : item->setFullScreen(false);
            }
        }
        object->rebuild();
        update();
    }
    QWidget::mouseDoubleClickEvent(event);
}

void MonitorDeviderItem::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    if(mSelected) {
        QPen pen;
        pen.setWidthF(3);
        pen.setColor(Qt::red);
        painter.setPen(pen);
    }
    if(mFullScreen) {
        QPen pen;
        pen.setWidthF(3);
        pen.setColor(Qt::blue);
        painter.setPen(pen);
    }
    painter.drawRect(rect().adjusted(0, 0, -1, -1));
}

bool MonitorDeviderItem::selected() const {
    return mSelected;
}

void MonitorDeviderItem::setSelected(bool newSelected) {
    mSelected = newSelected;
    update();
}

bool MonitorDeviderItem::fullScreen() const {
    return mFullScreen;
}

void MonitorDeviderItem::setFullScreen(bool newFullScreen) {
    mFullScreen = newFullScreen;
    update();
}
